package com.atguigu.gulimall.ssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * @Author : Jungle
 * @Description :
 */
@Controller
public class HelloController1 {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    /**
     * 无需登录就可以访问
     */
    @ResponseBody  //这个需要返回需要
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
    //感知这次是在ssoserver登录成功后返回
    //这里无需返回只是做跳转  无需 @ResponseBody
    @GetMapping("/boss")
    //token这个参数之后经过认证服务器才会带上
    public String employees(Model model, HttpSession session,
                            @RequestParam(value = "token",required = false) String token) {
        //token这个参数之后经过认证服务器才会带上
        if (!StringUtils.isEmpty(token)){
            // TODO: 2022/2/28 1、去ssoserver获取当前对应的真正对应的用户信息
            //这里不用openfeign调用
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> forEntity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token, String.class);
            String user = forEntity.getBody();

            session.setAttribute("loginUser",user);
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null) {
            //  没登录,跳转到登录服务器进行登录,
            //跳转过去后，使用url上的查询参数标识我们自己的是哪个页面
            //redirect_url=http://client1.com:8080/employees
            return "redirect:"+ssoServerUrl+"?redirect_url=http://client2.com:8082/boss";
        } else {
            List<String> emps = Arrays.asList("张三", "李四");
            model.addAttribute("emps", emps);
            return "list";
        }

    }
}
